﻿using HalconDotNet;
using LeaderCCSLaserUI.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using ViewROI;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs.VisionProgram
{
    public class FunctionBlobRectangleDialogViewModel : DialogViewModel
    {
        #region 变量        
        private HObject mImage;
        private readonly DrawROI drawROI;
        private bool isClosing = false;
        #endregion
        #region 属性
        private HImage cameraImage0;
        public HImage CameraImage0
        {
            get { return cameraImage0; }
            set { SetProperty(ref cameraImage0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }

        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private bool isDrawing;
        public bool IsDrawing
        {
            get { return isDrawing; }
            set { SetProperty(ref isDrawing, value); }
        }
        private BlobRectangleParam mBlobRectangleParam;
        public BlobRectangleParam MBlobRectangleParam
        {
            get { return mBlobRectangleParam; }
            set { SetProperty(ref mBlobRectangleParam, value); }
        }
        #endregion
        #region 函数
        private DelegateCommand openImageCommand;
        public DelegateCommand OpenImageCommand =>
            openImageCommand ?? (openImageCommand = new DelegateCommand(ExecuteOpenImageCommand));
        private DelegateCommand retateImageCommand;
        public DelegateCommand RetateImageCommand =>
            retateImageCommand ?? (retateImageCommand = new DelegateCommand(ExecuteRetateImageCommand));
        private DelegateCommand<object> operateCommandCommand;
        public DelegateCommand<object> OperateCommandCommand =>
            operateCommandCommand ?? (operateCommandCommand = new DelegateCommand<object>(ExecuteOperateCommandCommand));
        private DelegateCommand drawNiRegionCommand;
        public DelegateCommand DrawNiRegionCommand =>
            drawNiRegionCommand ?? (drawNiRegionCommand = new DelegateCommand(ExecuteDrawNiRegionCommand));
        private DelegateCommand drawModelPosCommand;
        public DelegateCommand DrawModelPosCommand =>
            drawModelPosCommand ?? (drawModelPosCommand = new DelegateCommand(ExecuteDrawModelPosCommand));
        private DelegateCommand actionComman;
        public DelegateCommand ActionCommand =>
            actionComman ?? (actionComman = new DelegateCommand(ExecuteActionCommand));

        void ExecuteActionCommand()
        {
            if (CameraImage0 != null)
            {
                try
                {
                    CameraAppendHObject0 = null;
                    CameraAppendHMessage0 = null;
                    HTuple row = new HTuple(MBlobRectangleParam.ST_Row), column = new HTuple(MBlobRectangleParam.ST_Column), angle = new HTuple(0), score = new HTuple(0), v1 = new HTuple(0), v2 = new HTuple(0);
                    HObject region, maxRegion;
                    HOperatorSet.GenEmptyObj(out region);
                    HOperatorSet.GenEmptyObj(out maxRegion);
                    var r = MFunc.FunDictionary["BlobRectangle"].Run(ref mImage, JsonConvert.SerializeObject(MBlobRectangleParam, Formatting.Indented), ref row, ref column, ref angle, ref score, ref maxRegion, ref region, ref v1, ref v2);
                    CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                    HOperatorSet.GenCrossContourXld(out var cross, MBlobRectangleParam.ST_Row, MBlobRectangleParam.ST_Column, 24, 0);
                    CameraAppendHObject0 = cross;
                    if (MBlobRectangleParam.IsCheckNi)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "cyan");
                        CameraAppendHObject0 = region;
                        CameraAppendHMessage0 = new HMsgEntry($"矩形面积:{v1.D:f0}", 10, 200, "cyan", "window", "box", "false", 16, "mono", "true", "false");
                    }
                    if (MBlobRectangleParam.IsCheckLasered)
                    {
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "fill");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "red");
                        CameraAppendHObject0 = maxRegion;
                        CameraAppendHMessage0 = new HMsgEntry($"焊点面积:{v2.D:f0}", 40, 200, "red", "window", "box", "false", 16, "mono", "true", "false");
                    }
                    if (!r)
                    {
                        CameraAppendHMessage0 = new HMsgEntry($"NG", 40, 40, "orange red", "window", "box", "false", 24, "mono", "true", "false");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDrawModelPosCommand()
        {
            try
            {
                if (CameraImage0 != null)
                {
                    CameraAppendHObject0 = null;
                    CameraAppendHMessage0 = null;
                    IsDrawing = true;
                    var roi = (ROICircle)drawROI.imageViewer.DrawROI(ROI.ROI_TYPE_CIRCLE);
                    IsDrawing = false;
                    if (!isClosing)
                    {
                        MBlobRectangleParam.ST_Row = roi.midR;
                        MBlobRectangleParam.ST_Column = roi.midC;
                        CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                        CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                        HOperatorSet.GenCrossContourXld(out var cross, roi.midR, roi.midC, 24, 0);
                        CameraAppendHObject0 = cross;
                    }
                }
                else
                {
                    MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteDrawNiRegionCommand()
        {
            if (CameraImage0 != null)
            {
                try
                {
                    CameraAppendHObject0 = null;
                    CameraAppendHMessage0 = null;
                    IsDrawing = true;
                    var roi = (ROIRectangle1)drawROI.imageViewer.DrawROI(ROI.ROI_TYPE_RECTANGLE1);
                    IsDrawing = false;
                    if (!isClosing)
                    {
                        MBlobRectangleParam.RecRow1 = roi.row1;
                        MBlobRectangleParam.RecColumn1 = roi.col1;
                        MBlobRectangleParam.RecRow2 = roi.row2;
                        MBlobRectangleParam.RecColumn2 = roi.col2;
                        CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                        CameraAppendHObject0 = roi.getRegion();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteOperateCommandCommand(object obj)
        {
            switch (obj.ToString())
            {
                case "确认":
                    {
                        try
                        {
                            string jsonString = JsonConvert.SerializeObject(MBlobRectangleParam, Formatting.Indented);
                            DialogParameters param = new DialogParameters();
                            param.Add("Parameter", jsonString);
                            OnRequestClose(new Prism.Services.Dialogs.DialogResult(ButtonResult.Yes, param));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    break;
                case "取消":
                    OnRequestClose(new Prism.Services.Dialogs.DialogResult(ButtonResult.Cancel));
                    break;
                default:
                    break;
            }
        }
        void ExecuteRetateImageCommand()
        {
            if (CameraImage0 != null)
            {
                HOperatorSet.RotateImage(CameraImage0, out mImage, 90, "constant");
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
            else
            {
                MessageBox.Show("图像不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteOpenImageCommand()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (mImage != null)
                {
                    mImage.Dispose();
                }
                HOperatorSet.ReadImage(out mImage, openFileDialog.FileName);
                CameraImage0 = new HImage(mImage.CopyObj(1, -1));
            }
        }
        #endregion
        #region 导航
        public override void OnDialogClosed()
        {
            isClosing = true;
            if (IsDrawing)
            {
                MFunc.HIOCancelDraw();
            }
        }
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            try
            {
                var jsonString = parameters.GetValue<string>("Parameter");
                MBlobRectangleParam = JsonConvert.DeserializeObject<BlobRectangleParam>(jsonString);
                var _image = parameters.GetValue<HObject>("Image");
                if (_image != null)
                {
                    mImage = _image.CopyObj(1, -1);
                    Task.Run(() =>
                    {
                        Thread.Sleep(100);
                        System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            CameraImage0 = new HImage(mImage.CopyObj(1, -1));

                            CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                            HOperatorSet.GenCrossContourXld(out var cross, MBlobRectangleParam.ST_Row, MBlobRectangleParam.ST_Column, 24, 0);
                            CameraAppendHObject0 = cross;
                            CameraGCStyle0 = new Tuple<string, object>("Color", "magenta");
                            HOperatorSet.GenRectangle1(out var rec1, MBlobRectangleParam.RecRow1, MBlobRectangleParam.RecColumn1, MBlobRectangleParam.RecRow2, MBlobRectangleParam.RecColumn2);
                            CameraAppendHObject0 = rec1;
                        }));
                    });
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                MBlobRectangleParam = new BlobRectangleParam {
                    IsCheckNi = true,
                    ClosingWidth = 3,
                    SelectRecAreaMin = 1000,
                    SelectRecAreaMax = 2000,
                    IsCheckLasered = true,
                    SelectLaserPadAreaMin = 500,
                    SelectLaserPadAreaMax = 1000,
                    ST_Row = 0,
                    ST_Column = 0,
                    RecRow1 = 0,
                    RecColumn1 = 0,
                    RecRow2 = 100,
                    RecColumn2 = 100
                };
            }
        }
        #endregion
        #region 构造函数
        public FunctionBlobRectangleDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "Blob矩形功能";
            IsDrawing = false;
            drawROI = containerProvider.Resolve<DrawROI>();
        }
        #endregion

    }
}
